import os
from typing import Optional
from dotenv import load_dotenv
from peewee import MySQLDatabase, SqliteDatabase

# Load environment variables from .env file
load_dotenv()

class Config:
    """Application configuration class"""
    
    # Database Configuration
    DB_HOST: str = os.getenv('DB_HOST', 'localhost')
    DB_PORT: int = int(os.getenv('DB_PORT', '3306'))
    DB_NAME: str = os.getenv('DB_NAME', 'eeg_signal_dispatcher')
    DB_USER: str = os.getenv('DB_USER', 'root')
    DB_PASSWORD: str = os.getenv('DB_PASSWORD', 'password')
    

    
    # FastAPI Configuration
    API_HOST: str = os.getenv('API_HOST', '0.0.0.0')
    API_PORT: int = int(os.getenv('API_PORT', '8000'))
    API_DEBUG: bool = os.getenv('API_DEBUG', 'True').lower() == 'true'
    API_RELOAD: bool = os.getenv('API_RELOAD', 'True').lower() == 'true'
    
    # Application Configuration
    APP_NAME: str = os.getenv('APP_NAME', 'EEG Signal Dispatcher')
    APP_VERSION: str = os.getenv('APP_VERSION', '1.0.0')
    APP_DESCRIPTION: str = os.getenv('APP_DESCRIPTION', 'EEG Signal Processing and Dispatching System')
    
    # Security Configuration
    SECRET_KEY: str = os.getenv('SECRET_KEY', 'your-secret-key-here-change-in-production')
    ACCESS_TOKEN_EXPIRE_MINUTES: int = int(os.getenv('ACCESS_TOKEN_EXPIRE_MINUTES', '30'))
    
    # Logging Configuration
    LOG_LEVEL: str = os.getenv('LOG_LEVEL', 'INFO')
    LOG_FILE: str = os.getenv('LOG_FILE', 'logs/app.log')
    
    # EEG Signal Processing Configuration
    SIGNAL_BUFFER_SIZE: int = int(os.getenv('SIGNAL_BUFFER_SIZE', '1000'))
    SAMPLING_RATE: int = int(os.getenv('SAMPLING_RATE', '256'))
    PROCESSING_INTERVAL: float = float(os.getenv('PROCESSING_INTERVAL', '1.0'))
    
    @classmethod
    def get_database_url(cls) -> str:
        """Get database connection URL"""
        return f"mysql://{cls.DB_USER}:{cls.DB_PASSWORD}@{cls.DB_HOST}:{cls.DB_PORT}/{cls.DB_NAME}"
    


# Global configuration instance
config = Config()

# Database instance
_database = None

def get_database():
    """Get database connection"""
    global _database
    if _database is None:
        # Use MySQL database
        _database = MySQLDatabase(
            Config.DB_NAME,
            user=Config.DB_USER,
            password=Config.DB_PASSWORD,
            host=Config.DB_HOST,
            port=Config.DB_PORT,
            charset='utf8mb4'
        )
    return _database

def reset_database():
    """Reset database connection (for switching database types)"""
    global _database
    if _database and not _database.is_closed():
        _database.close()
    _database = None

def close_database():
    """Close database connection"""
    global _database
    if _database and not _database.is_closed():
        _database.close()
        _database = None